import { Request, Response, NextFunction } from 'express';
import _ from 'lodash';
import { getSwiper, getIdSwiper, createSwiper, updateSwiper, deleteSwiper, findFileById, createFile, deleteFileById } from './swiper.service';

/**
 * 获取内容
 */
export const index = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  const { pageNo, pageSize, status, category, type } = request.query;

  try {
    const data = await getSwiper(parseInt(`${pageNo}`), parseInt(`${pageSize}`), parseInt(`${status}`), parseInt(`${category}`), parseInt(`${type}`));
    
    response.send(data);
  } catch (error) {
    next(error);
  }
}

/**
 * 获取内容
 */
export const home = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 1: 首页，2: 动作片，3：推荐，4：喜剧，5：科幻，6：卡通
  let action = 2;
  let recommend = 3;
  let comedy = 4;
  let sciencefiction = 5;
  let cartoon = 6;

  try {
    // 动作片轮播图
    const actionData = await getIdSwiper(parseInt(`${action}`));

    // 推荐片轮播图
    const recommendData = await getIdSwiper(parseInt(`${recommend}`));

    // 喜剧片轮播图
    const comedyData = await getIdSwiper(parseInt(`${comedy}`));

    // 科幻片轮播图
    const sciencefictionData = await getIdSwiper(parseInt(`${sciencefiction}`));

    // 卡通片轮播图
    const cartoonData = await getIdSwiper(parseInt(`${cartoon}`));

    response.send({ actionData, recommendData, comedyData, sciencefictionData, cartoonData });
  } catch (error) {
    next(error);
  }
}

/**
 * 获取内容(按 ID 查找)
 */
export const swiperDetail = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取内容 ID
  const { postId } = request.params;

  // 调取内容
  try {
    const data = await getIdSwiper(parseInt(postId, 10));
    
    // 做出响应
    response.send(data);
  } catch (error) {
    next(error);
  }
};

/**
 * 创建内容
 */
export const store = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取创建内容
  const swiperModel = request.body;
  let date = Math.floor(new Date().getTime())
  swiperModel.releaseTime = date;

  if (swiperModel.id && swiperModel.id > 0) {
    const data = await updateSwiper(swiperModel, parseInt(swiperModel.id, 10));
    response.send(data);
  } else {

    // 创建
    try {
      const data = await createSwiper(swiperModel);
      response.send(data);
    } catch (error) {
      next(error);
    }
  }
}

/**
 * 更新内容
 */
export const update = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取更新内容 ID
  const { postId } = request.params;

  // 获取更新内容
  const post = _.pick(request.body, ['content','image_id']);

  // 更新
  try {
    const data = await updateSwiper(post, parseInt(postId, 10));
    response.send(data);
  } catch (error) {
    next(error);
  }
}

/**
 * 状态
 */
export const status = async (
  request: Request,
  response: Response,
  next: NextFunction,
) => {
  // 获取内容 ID
  const { postId } = request.body;

  // 获取内容
  const post = _.pick(request.body, ['status']);

  // 执行
  try {
    const data = await updateSwiper(post as any, parseInt(postId, 10));
    response.send(data);
  } catch (error) {
    next(error);
  }
};

/**
 * 删除内容
 */
export const destroy = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取删除内容 ID
  const { postId } = request.body;

  // 删除
  try {
    const data = await deleteSwiper(parseInt(postId, 10));
    response.send(data);
  } catch (error) {
    next(error);
  }
}

/**
 * 上传文件
 */
export const uploads = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取类型
  let { target_type, target_id } = request.body;
  if (target_id === undefined) {
    target_type = 21;
  }


  // 文件信息
  const fileInfo = _.pick(request.file, [
    'id',
    'target_id',
    'target_type',
    'url',
    'originalname',
    'mimetype',
    'filename',
    'size'
  ])

  fileInfo['url'] = "/swiper/";
  fileInfo['target_type'] = parseInt(`${target_type}`, 10);

  try {
    // 保存文件信息
    const data = await createFile({
      ...fileInfo,
      //target_type: parseInt(`${target_type}`, 10), // target_type: `${target_type}` // target_type: target_type as string  转换字符串两种写法
    })

    let image_id = (data as any).insertId
    if (image_id && image_id > 0) {
      let fileData = await findFileById(image_id, 0, 0)
      data['image'] = fileData
    }

    // 做出响应
    response.status(200).send(data)
  } catch (error) {
    next(error);
  }
}

/**
 * 文件服务
 */
export const serve = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 从地址参数里得到文件 ID
  const { fileId } = request.params;

  try {
    // 查找文件信息
    const file = await findFileById(parseInt(fileId, 10), 0, 0);

    // 做出响应
    response.sendFile(file.filename, {
      root: 'uploads/swiper',
      headers: {
        'Content-Type': file.mimetype
      }
    });
  } catch (error) {
    next(error);
  }
}

/**
 * 获取文件名
 */
export const getFileName = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取文件 ID
  const { fileId } = request.body;
  let file = await findFileById(fileId, 0, 0)
  if (!file || file.length <= 0) {
    response.send({
      status: 2,
      msg: 'not found'
    })
    return;
  }
  let result = await deleteFileById(file[0])

  response.send({
    status: 1,
    msg: 'ok'
  })

}
